from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.contrib import messages
from django.views.generic import DetailView, ListView, CreateView, UpdateView, DeleteView
from django.views.generic.edit import FormMixin
from django.urls import reverse_lazy
from django.utils import timezone


from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import Post, MRCAnswer
from .forms import AnswerForm
from .serializers import PostSerializer, MRCAnswerSerializer



# class PostListView(ListView):
#     '''
#     首页展示视图
#     '''
#     model = Post
#     paginate_by = 5
#     template_name = 'index.html'
#     context_object_name = 'posts'
#     # ordering = ['-date_posted']

#     def get_queryset(self):
#         # https://docs.djangoproject.com/zh-hans/3.1/topics/class-based-views/generic-display/#dynamic-filtering
#         # self.locate_id = get_object_or_404(Post, name=self.kwargs['locate_id'])
#         self.locate_id = self.request.GET.get('locate_id', -1)
#         if self.locate_id == -1:
#             return Post.objects.all().order_by('-date_posted')
#         else:
#             return Post.objects.filter(locate_id=self.locate_id)

class PostListView(ListView):
    '''
    首页展示视图
    '''
    model = Post
    paginate_by = 5
    template_name = 'index.html'
    context_object_name = 'posts'
    # ordering = ['-date_posted']

    def get_queryset(self):
        # https://docs.djangoproject.com/zh-hans/3.1/topics/class-based-views/generic-display/#dynamic-filtering
        # self.locate_id = get_object_or_404(Post, name=self.kwargs['locate_id'])
        self.locate_id = self.request.GET.get('locate_id', -1)
        self.askorsearch = self.request.GET.get('askorsearch', False)
        self.question = self.request.GET.get('question', False)
        page = self.request.GET.get('page', -1)

        if self.locate_id != -1:
            return Post.objects.filter(locate_id=self.locate_id)
        elif self.askorsearch == 'search':
            if self.question is not None:
                return Post.objects.filter(question__contains=self.question).order_by('-date_posted')

        return Post.objects.all().order_by('-date_posted')
        # return super(PostListView, self).get_queryset()

    def get(self, request, *args, **kwargs):
        askorsearch = request.GET.get('askorsearch', False)
        

        if askorsearch == 'ask':
            question = request.GET.get("question", False)

            if question:
                l = Post.objects.filter(question=question)
                if len(l) > 0:
                    l[0].date_posted = timezone.now()
                    l[0].save()
                else:
                    post = Post.objects.create(
                        question=question,
                        author = self.request.user if self.request.user.is_authenticated else User.objects.get(id=2),
                        )
                    post.save()
            
        return super(PostListView, self).get(request, *args, **kwargs)


class PostDetailView(FormMixin, DetailView):
    '''
    问题详情视图
    '''
    model = Post
    template_name = 'detail.html'
    context_object_name = 'post'
    form_class = AnswerForm

    def get_success_url(self):
        return reverse_lazy('detail', kwargs={'pk': self.object.pk})

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponseForbidden
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        new_answer = form.save(commit=False)
        new_answer.author = self.request.user
        new_answer.question = self.object
        # new_answer.question_id = 
        new_answer.save()
        
        return super().form_valid(form)


    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        # 返回相关的答案
        post_id = int(self.request.path[6:-1])
        answers = Post.objects.get(id=post_id).answers.all()
        context['answers'] = answers
        mrc_answers = Post.objects.get(id=post_id).mrc_answers.all()
        context['mrc_answers'] = mrc_answers
        for answer in mrc_answers:
            temp = answer.context
            start, end = answer.start, answer.end
            left, right = '<strong>', '</strong>'
            temp = list(temp)
            temp.insert(end, right)
            temp.insert(start, left)
            answer.context = ''.join(temp)

        # # 增加回答表单
        # new_answer = AnswerForm()
        # context['answer_form'] = new_answer
        return context


# class PostCreateView(LoginRequiredMixin, CreateView):
class PostCreateView(CreateView):
    '''
    发布问题视图
    '''
    model = Post
    template_name = 'create.html'
    fields = ['question', 'locate_id']

    def get_initial(self):
        '''根据 get 请求预先填写问题'''
        question = self.request.GET.get('question', '')
        return {'question': question} if question else {}

    def form_valid(self, form):
        '''在进行验证之前先增加author，需要先创建id为2的匿名用户。'''
        if self.request.user.is_authenticated:
            form.instance.author = self.request.user
        else:
            form.instance.author = User.objects.get(id=2)
        return super().form_valid(form)


class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    '''
    问题更新视图
    '''
    model = Post
    template_name = 'update.html'
    fields = ['question']

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    '''
    问题删除视图
    '''
    model = Post
    template_name = 'delete.html'
    success_url = reverse_lazy('home')

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


# RESTFUL API HERE
# @api_view(['GET','POST'])
@api_view(['GET'])
def question_list(request, format=None):

    if request.method == 'GET':
        questions = Post.objects.all()
        serializer = PostSerializer(questions, many=True)
        return Response(serializer.data)

@api_view(['GET', 'PUT', 'DELETE'])
def question_detail(request, pk, format=None):
    """
    Retrieve，update or delete an article instance。"""
    try:
        question = Post.objects.get(pk=pk)
    except Post.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = PostSerializer(question)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = PostSerializer(question, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # elif request.method == 'DELETE':
    #     question.delete()
    #     return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'POST'])
def answer_list(request, format=None):

    if request.method == 'GET':
        answers = MRCAnswer.objects.all()
        serializer = MRCAnswerSerializer(answers, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = MRCAnswerSerializer(data=request.data)
        if serializer.is_valid():
            # Very important. Associate request.user with author
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
